<template>
    <view class="activity-page">
        <!-- 下拉刷新 -->
        <scroll-view 
            class="refresh-container" 
            scroll-y="true" 
            refresher-enabled="true"
            :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresh"
        >
            <!-- 搜索栏 -->
            <view class="search-bar">
            <uni-icon name="search" class="search-icon"></uni-icon>
            <input 
                type="text" 
                placeholder="搜索活动" 
                v-model="searchValue" 
                class="search-input"
            />
            <button class="search-button" @click="performSearch">搜 索</button>
            <view class="toggle-button" @click="toggleChart">
                <view class="arrow-icon" :class="{ 'arrow-up': isChartExpanded, 'arrow-down': !isChartExpanded }">
                </view>
            </view>
        </view>
                
        <!-- 活动类型图表 -->
        <view class="chart-container" :class="{ 'chart-collapsed': !isChartExpanded }" :style="{ 'pointer-events': isChartExpanded ? 'auto' : 'none' }">
            <view class="chart-item" :class="{ 'active': selectedCreditType === '思想成长' }" @click="handleCreditTypeClick('思想成长')">
                <image src="@/static/activity_icon/思想.png" class="icon"></image>
                <text class="chart-text">思想成长</text>
            </view>
            <view class="chart-item" :class="{ 'active': selectedCreditType === '劳动教育' }" @click="handleCreditTypeClick('劳动教育')">
                <image src="@/static/activity_icon/劳动.png" class="icon"></image>
                <text class="chart-text">劳动教育</text>
            </view>
            <view class="chart-item" :class="{ 'active': selectedCreditType === '社会实践' }" @click="handleCreditTypeClick('社会实践')">
                <image src="@/static/activity_icon/社会.png" class="icon"></image>
                <text class="chart-text">社会实践</text>
            </view>
            <view class="chart-item" :class="{ 'active': selectedCreditType === '创新创业' }" @click="handleCreditTypeClick('创新创业')">
                <image src="@/static/activity_icon/创新.png" class="icon"></image>
                <text class="chart-text">创新创业</text>
            </view>

            <view class="chart-item" :class="{ 'active': selectedCreditType === '工作履历' }" @click="handleCreditTypeClick('工作履历')">
                <image src="@/static/activity_icon/工作履历.png" class="icon"></image>
                <text class="chart-text">工作履历</text>
            </view><view class="chart-item" :class="{ 'active': selectedCreditType === '文体活动' }" @click="handleCreditTypeClick('文体活动')">
                <image src="@/static/activity_icon/文体活动.png" class="icon"></image>
                <text class="chart-text">文体活动</text>
            </view><view class="chart-item" :class="{ 'active': selectedCreditType === '实践实习' }" @click="handleCreditTypeClick('实践实习')">
                <image src="@/static/activity_icon/实践实习.png" class="icon"></image>
                <text class="chart-text">实践实习</text>
            </view><view class="chart-item" :class="{ 'active': selectedCreditType === '' }" @click="handleCreditTypeClick('')">
                <image src="@/static/activity_icon/全部类型.png" class="icon"></image>
                <text class="chart-text">全部类型</text>
            </view>
        </view>
       
        <!-- 分类标签 -->
        <view class="category-tabs">
            <view 
                v-for="tab in tabs" 
                :key="tab.value"
                :class="['tab-item', activeTab === tab.value ? 'tab-active' : 'tab-default']"
                @click="switchTab(tab.value)">
                {{ tab.label }}
            </view>
            <!-- 跳转我的活动 -->
            <view class="my-activity-btn" @click="gotoMyActivity">我的活动</view>
        </view>
        
        

        <!-- 活动列表 -->
            <ActivityList
                :filtered-activities="filteredActivities"
                :has-more="hasMore"
                @load-more="onLoadMore"
                @activity-click="gotoActivity"
                @scroll="handleScroll"
            />
        </scroll-view>
    </view>

</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getActivityList } from '@/api/wlxz/act_list';
import { useActivityStore } from '@/store/modules/activity/activity.js';
import ActivityList from '@/components/ActivityList/ActivityList.vue';

// 搜索值
const searchValue = ref('');

// 实际搜索关键词
const actualSearchKeyword = ref('');

// 图表展开状态
const isChartExpanded = ref(false);

// 当前选中的活动类型
const selectedCreditType = ref('');

// 切换图表展开/收起状态
const toggleChart = () => {
    isChartExpanded.value = !isChartExpanded.value;
    // selectedCreditType.value = '';   我感觉加这个多余

};

// 处理活动类型点击事件
const handleCreditTypeClick = (creditType) => {
    selectedCreditType.value = creditType;
    console.log(selectedCreditType.value);
};

// 执行搜索
const performSearch = () => {
    actualSearchKeyword.value = searchValue.value;
};

// 当前选中标签
const activeTab = ref('all');



// 活动数据 - 根据后端字段映射
const activities = ref([]);
const isRefreshing = ref(false);
const pageNum = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);

// 使用活动store
const activityStore = useActivityStore();

// 分类标签数据
const tabs = [
    { value: 'all', label: '全部' },
    { value: '规划中', label: '规划中' },
    { value: '报名中', label: '报名中' }
];
// 筛选活动
const filteredActivities = computed(() => {
    let filtered = activities.value;
    
    // 根据活动类型筛选
    if (selectedCreditType.value) {
        filtered = filtered.filter(item => 
            item.category && item.category.includes(selectedCreditType.value)
        );
    }
    
    // 根据标签筛选
    if (activeTab.value !== 'all') {
        const statusMap = {
            '规划中': '规划中',
            '报名中': '报名中', 
            '等待中': '等待中',
            '已结束': '已结束',
            '已补录': '已补录',
            '进行中': '进行中'
        };
        const targetStatus = statusMap[activeTab.value];
        if (targetStatus) {
            filtered = filtered.filter(item => item.status === targetStatus);
        }
    }
    
    // 根据搜索关键词筛选
    if (actualSearchKeyword.value.trim()) {
        const keyword = actualSearchKeyword.value.toLowerCase();
        filtered = filtered.filter(item => 
            item.title.toLowerCase().includes(keyword) ||
            item.location.toLowerCase().includes(keyword)
        );
    }
    
    // 按开始时间降序排序
    return filtered.sort((a, b) => {
        try {
            // 直接使用活动开始时间进行排序，不再使用split方法
            if (!a.dateRange || !b.dateRange) {
                return 0; // 如果任一活动日期为空，保持原顺序
            }
            
            const dateA = new Date(a.dateRange);
            const dateB = new Date(b.dateRange);
            
            // 检查日期是否有效
            if (isNaN(dateA.getTime()) || isNaN(dateB.getTime())) {
                return 0; // 如果日期无效，保持原顺序
            }
            
            return dateB - dateA; // 降序排序，最新的活动在前
        } catch (e) {
            console.error('日期排序错误:', e);
            return 0; // 如果解析失败，保持原顺序
        }
    });
});
// 将后端数据转换为前端显示格式
const transformActivityData = (backendData) => {
    if (!Array.isArray(backendData)) {
        console.warn('transformActivityData: 期望数组类型，实际收到:', typeof backendData);
        return [];
    }
    
    return backendData.filter(item => item && typeof item === 'object').map(item => ({
        activityId: item.activityId || '',
        title: item.activityName || '未命名活动',
        dateRange: item.activityStart,
        category: item.creditType || '',//学分类型
        status: item.status || '0',  
        location: item.activityLocation || '未知地点',//活动地点
        creditValue: item.creditValue || 0,//发放分值
        participantLimit: item.participantLimit || 0,//人数限制
        responsiblePerson: item.responsiblePerson || '',//负责人
        supervisor: item.supervisor || '',//负责导师
        registrationStart: item.registrationStart,//报名开始时间
        registrationEnd: item.registrationEnd,//报名结束时间

    }));
};
//请求接口，并返回处理数据进行展示，
const loadActivities = async()=>{
    try {
        const response = await activityStore.loadActivities({
            // pageNum: 1,
            // pageSize: 10
            // status: activeTab.value === 'all' ? null : activeTab.value,
        });
        
        if (response.code === 200) {
            // 使用transformActivityData转换后端数据
            console.log(response.data)
            activities.value = transformActivityData(response.data);
        } else {
            console.log(response.code)
            uni.showToast({
                title: response.msg || '获取活动列表失败',
                icon: 'none'
            });
        }
    } catch (error) {
        console.error('获取活动列表失败:', error);
        console.log("错误")
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        });
    }
}

// 切换标签
const switchTab = (tab) => {
    activeTab.value = tab;
};

// 处理ActivityList组件滚动，当用户滚动活动列表时自动收起图表
const handleScroll = (e) => {
    // 只有在图表展开状态下才处理滚动事件
    if (isChartExpanded.value) {
        // 设置一个滚动阈值，当滚动超过一定距离时收起图表
        const scrollTop = e.detail.scrollTop;
        if (scrollTop > 30) { // 滚动超过30rpx时收起图表
            isChartExpanded.value = false;
        }
    }
};

// 前往活动详情
const gotoActivity = (id) => {
    uni.navigateTo({
        url: `/pages_activity/pages/details/index?id=${id}`
    });
};
// 前往我的活动
const gotoMyActivity = () => {
    uni.navigateTo({
        url: `/pages_activity/pages/participant/index`
    });
};
// 下拉刷新
const onRefresh = async () => {
    isRefreshing.value = true;
    pageNum.value = 1;
    hasMore.value = true;
    
    try {
        const response = await activityStore.loadActivities({
            pageNum: pageNum.value,
            pageSize: pageSize.value
        });
        
        if (response.code === 200) {
            activities.value = transformActivityData(response.data);
        }
    } catch (error) {
        console.error('刷新活动列表失败:', error);
    } finally {
        isRefreshing.value = false;
    }
};

// 上拉加载更多
const onLoadMore = async () => {
    if (!hasMore.value) return;
    
    try {
        pageNum.value++;
        const response = await getActivityList({
            pageNum: pageNum.value,
            pageSize: pageSize.value
        });
        
        if (response.code === 200) {
            const newActivities = transformActivityData(response.data);
            if (newActivities.length < pageSize.value) {
                hasMore.value = false;
            }
            activities.value.push(...newActivities);
        }
    } catch (error) {
        console.error('加载更多活动失败:', error);
        pageNum.value--;
    }
};

// 页面加载时获取活动列表
onMounted(() => {
    loadActivities();
});
</script>

<style scoped>
/* 页面样式 - 预留位置 */
.activity-page {
    padding: 16rpx;
    height: 100vh;
    display: flex;
    flex-direction: column;
}

/* 下拉刷新容器样式 */
.refresh-container {
    flex: 1;
    height: 100%;
}

/* 图表容器样式 */
.chart-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    background: white;
    border-radius: 30rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease-in-out;
    overflow: visible;
    max-height: 500rpx; /* 设置足够大的最大高度 */
}

/* 图表容器收起状态 */
.chart-collapsed {
    max-height: 0;
    padding-top: 0;
    padding-bottom: 0;
    margin-bottom: 0;
    opacity: 0;
}

/* 图表项样式 */
.chart-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 25%;
    margin-bottom: 20rpx;
    padding: 15rpx 10rpx;
    border-radius: 20rpx;
    transition: all 0.2s ease;
    cursor: pointer;
}

/* 图表项选中状态 */
.chart-item.active {
    background-color: rgba(0, 122, 255, 0.1);
    transform: scale(1.05);
}

.chart-item:hover {
    background-color: rgba(0, 122, 255, 0.05);
}

.chart-item.active:hover {
    background-color: rgba(0, 122, 255, 0.15);
}

/* 图标样式 */
.icon {
    width: 110rpx;
    height: 110rpx;
    margin-bottom: 10rpx;
}

/* 图表文字样式 */
.chart-text {
    font-size: 27rpx;
    color: #333;
    text-align: center;
}



/* 分类标签样式 */
.category-tabs {
    display: flex;
    flex-wrap: wrap;
    background: white;
    border-radius: 16rpx;
    padding: 16rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
    padding: 10rpx 18rpx;
    margin: 0 10rpx;
    font-size: 26rpx;
    font-weight: 580;
    transition: color 0.3s ease, transform 0.3s ease;
    color: #000000;
    position: relative;
}

.tab-active {
    color: rgba(0, 122, 255, 100);
    transform: translateY(-2rpx);
}

.tab-active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 3rpx;
    background-color: rgba(0, 122, 255, 100);
    animation: slideIn 0.3s ease forwards;
}

@keyframes slideIn {
    from {
        width: 0;
        left: 50%;
    }
    to {
        width: 100%;
        left: 0;
    }
}

/* 搜索栏样式 */
.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    background: white;
    border-radius: 30rpx;
    padding: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

/* 搜索图标样式 */
.search-icon {
    margin-right: 10rpx;
    color: #999;
    font-size: 32rpx;
}

/* 搜索输入框样式 */
.search-input {
    flex: 1;
    height: 60rpx;
    font-size: 28rpx;
    background: #f5f5f5;
    border-radius: 30rpx;
    padding: 0 20rpx 0 50rpx;
    position: relative;
}

/* 搜索输入框内的放大镜样式 */
.search-input::before {
    content: "🔍";
    position: absolute;
    left: 15rpx;
    top: 50%;
    transform: translateY(-50%);
    font-size: 28rpx;
    color: #999;
}

/* 搜索按钮样式 */
.search-button {
    margin-left: 10rpx;
    padding: 0 30rpx;
    height: 60rpx;
    line-height: 60rpx;
    background: white;
    color: black;
    border-radius: 30rpx;
    font-size: 27rpx;
    font-weight: 500;
    border: none;
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
}

/* 展开/收起按钮样式 */
.toggle-button {
    display: flex;
    align-items: center;
    margin-left: 10rpx;
    padding: 0 20rpx;
    height: 60rpx;
    background: rgba(230, 242, 255, 100);
    color: rgba(0, 122, 255, 100);
    border-radius: 30rpx;
    font-size: 24rpx;
    font-weight: 500;
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
}

.toggle-icon {
    margin-left: 6rpx;
    font-size: 24rpx;
}

.toggle-text {
    margin-right: 10rpx;
    font-size: 24rpx;
}

/* 箭头图标样式 */
.arrow-icon {
    width: 0;
    height: 0;
    border-left: 12rpx solid transparent;
    border-right: 12rpx solid transparent;
    transition: all 0.3s ease;
}

/* 向上箭头 */
.arrow-up {
    border-bottom: 12rpx solid white;
}

/* 向下箭头 */
.arrow-down {
    border-top: 12rpx solid white;
}

.my-activity-btn {
    margin-left: auto;
    padding: 12rpx 26rpx;
    background: rgba(230, 242, 255, 100);
    color: rgba(0, 122, 255, 100);
    border-radius: 20rpx;
    font-size: 25rpx;
    font-weight: 500;
    white-space: nowrap;
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
}

/* 空状态样式 */
.empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400rpx;
    background: linear-gradient(135deg, #f8f9ff, #e9ecef);
    border-radius: 20rpx;
    margin: 40rpx 20rpx;
}

.empty-text {
    font-size: 32rpx;
    color: #8e9aaf;
    font-weight: 500;
}

/* 加载提示样式 */
.refresh-loading {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40rpx 0;
    color: #999;
    font-size: 28rpx;
}

.refresh-text {
    margin-left: 10rpx;
}

.loading-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40rpx 0;
    color: #999;
    font-size: 28rpx;
}

.loading-text {
    margin-left: 10rpx;
}

.bottom-hint {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40rpx 0;
    color: #ccc;
    font-size: 26rpx;
}

.bottom-text {
    position: relative;
}

.bottom-text::before,
.bottom-text::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 60rpx;
    height: 1rpx;
    background-color: #ddd;
}

.bottom-text::before {
    left: -80rpx;
}

.bottom-text::after {
    right: -80rpx;
}

</style>